<?php
namespace app\index\controller;
use think\Controller ;
use Db;
use EasyWeChat\Factory;

class Index extends Controller
{
    public function index()
    {

//        $this->authLogin();
        $type = input('type');

        if(!$type){
            $type = Db::name('nav_type')->where(['status'=>1,'pid'=>0])->order('rank desc,id desc')->value('id');
        }

        //轮播图
        $slide = DB::name('advert')->field('id,image,type,link,title')
            ->where('site=1 AND status=1 AND (type='.$type.' or type=0)')
            ->select();
        $this->assign('slide',$slide);


        $ad = Db::name('advert')
            ->field('id,link,image,title')
            ->where('site=2 AND status=1 AND (type='.$type.' or type=0)')->order('type desc,id desc')->find();

        $this->assign('ad',$ad);


        $this->assign('type',$type);


        $img_path = config('api.oss_img_path');
        $this->assign('img_path',$img_path);


        $otherList = Db::name('nav')->field('id,nav_name,url')->where(['status'=>1,'type'=>$type])->select();
        $this->assign('otherList',$otherList);

        $types = getTypes();
        $this->assign('types',$types);

        if($types[0]['id']==$type){

            //二级链接
            $sons = Db::name('nav_type')->field('id,image,type_name')
                ->where(['pid'=>$type,'status'=>1])->order('rank desc,id desc')->limit(1)->select();


            //推荐分类列表
            $typeList = Db::name('nav_type')->alias('a')->field('a.id,a.type_name,a.image,a.eid,b.title')
                ->leftJoin('explain b','a.eid=b.id')
                ->where(['a.status'=>1,'a.is_show'=>1,'a.pid'=>$type])
                ->where('a.id','<>',$sons[0]['id'])
                ->select();

            foreach($typeList as $k=> &$v){

                $v['navList'] = Db::name('nav')->alias('a')->field('a.nav_name,a.url,a.id')
                                    ->leftJoin('nav_type b','a.type=b.id')
                                    ->where('(a.type='.$v['id'].' OR b.pid='.$v['id']. ') AND a.status=1')
                                    ->order('a.rank desc,a.id desc')
                                    ->limit(6)
                                    ->select();


                if(!$v['navList']){
                    unset($typeList[$k]);
                }
            }

            $this->assign('typeList',$typeList);
        }else{
            //二级链接
            $sons = Db::name('nav_type')->field('id,image,type_name')
                ->where(['pid'=>$type,'status'=>1])->order('rank desc,id desc')->select();


        }
        foreach($sons as &$v){
            $v['navList'] = Db::name('nav')->field('id,nav_name,url')->where(['type'=>$v['id'],'status'=>1])->select();
        }
        $this->assign('sons',$sons);


        $explain = Db::name('config')->where('key','explain')->value('value');
        $this->assign('explain',$explain);
        return $this->fetch();
    }
    public function test(){
        return $this->fetch();
    }

    public function download(){

        return $this->fetch();


        $this->redirect($url);
    }
    public function downloadApp(){

        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){

            $url = Db::name('config')->where(['key'=>'apple_app'])->value('value');
            $this->redirect($url);

//        }else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android')){
//            echo 'systerm is Android';
        }else{
//            $url = Db::name('config')->where(['key'=>'android_app'])->value('value');

            ob_clean();

            $filename='掌间在线app.apk';
            $filepath='upload/app.apk';

//            $filename=iconv("UTF-8","GB2312",$filename);


            //判断路径是否存在

            if(!file_exists($filepath)){
                echo "文件不存在";
                return;
            }

//            $fp=fopen($filepath,"r");

            //取得文件大小
            $file_Size=filesize($filepath);
//            Header("Content-type: application/vnd.android.package-archive");
            Header("Content-type: application/vnd.android.package-archive");
            header("Content-type:application/octet-stream");
            header("Accept-Ranges:bytes");
            header("Accept-Length:".$file_Size);
            header("Content-Disposition: attachment; filename=".$filename);
            @readfile($filepath);
            exit ();
            $buffer=1024;
            $buffer_count=0;

            while(!feof($fp)&&$file_Size-$buffer_count>0){
                $data=fread($fp,$buffer);
                $buffer_count+=$buffer;
                echo $data;

            }

            fclose($fp);

        }

    }


    public function iframe(){

        $title = input('title');

        $this->assign('title',$title);
        $type = input('type');
        $url = input('url');
        $id = input('id');

        $ip = ip2long(request()->ip());


        if($type && $id){

            $today = strtotime('today');
            $time = time();
            $row = Db::name('look_record')->field('id')->where(['ip' => $ip, 'aid' => $id,'type'=>$type])->find();


            if ($row) {

                $rowToday = Db::name('look_record')->field('id,hits')
                    ->where('update_time','>=',$today)->where(['ip' => $ip, 'aid' => $id,'type'=>$type])->find();


                if($type==1){
                    Db::name('advert')->where('id', $id)->setInc('hits', 1);

                }else{
                    Db::name('nav')->where('id', $id)->setInc('pv', 1);

                }

                if($rowToday){
                    Db::name('look_record')->where('id',$rowToday['id'])
                        ->update([
                            'hits'=>$rowToday['hits']+1,
                            'update_time'=>$time
                        ]);
                }else{
                    $addData = [
                        'aid' => $id,
//                    'uid' => $this->uid,
                        'ip' => $ip,
                        'update_time'=>$time,
                        'type'=>$type,
                        'hits'=>1
                    ];

                    Db::name('look_record')->insert($addData);
                }

            } else {
                if($type==1) {

                    Db::name('advert')->where('id', $id)->inc('hits')->inc('people_hits')->update();

                }else{

                    Db::name('nav')->where('id', $id)->inc('pv')->inc('uv')->update();

                }

                $addData = [
                    'aid' => $id,
//                    'uid' => $this->uid,
                    'ip' => $ip,
                    'update_time'=>$time,
                    'type'=>$type,
                    'hits'=>1
                ];

                Db::name('look_record')->insert($addData);

            }

        }


        $this->assign('type',$type);
        $this->assign('url',$url);
        $this->assign('id',$id);
        return $this->fetch();
    }


    //公告栏
    public function notice(){

        $list = Db::name('explain')->field('id,title')->where('status',1)->order('id desc')->select();

        $this->assign('list',$list);

        return $this->fetch();
    }


    //公告栏
    public function noticeDetails(){


        $content = Db::name('explain')->where(['status'=>1,'id'=>input('id')])->find();


        $this->assign('content',$content);

        return $this->fetch();
    }

    //公告栏
    public function notes(){


        $content = Db::name('nav_type')->where(['status'=>1,'id'=>input('id')])->find();

        if(input('test')==1){
            dump($content['notes']);exit;
        }
        $this->assign('type',$content);

        return $this->fetch();
    }

    //微信授权回调
    public function wxLogin(){


        $config = [
            'app_id' => config('wechat.AppId'),
            'secret' => config('wechat.AppSecret'),
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];


        $token = cookie('ticket');

        if($token){

            $row = Db::name('user')->where('login_token',$token)->find();

            if($row){
                $this->redirect('/index/index');
                exit;
            }
        }

        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user()->toArray();

        $time = time();
        $info = array(
            'nickname'=>$user['nickname'],
            'avatar'  =>$user['avatar'],
            'wx_nickname'=>$user['nickname'],
            'wx_avatar'  =>$user['avatar'],
            'wx_openid'  =>$user['id'],
            'sex'  =>$user['original']['sex'],
            'login_token' => MD5($user['id'].'@#$%8'.$time),
            'login_time' =>$time,
        );


        $row = Db::name('user')->where('wx_openid',$user['id'])->find();

        if($row){

            unset($user['nickname']);
            Db::name('user')->where('wx_openid',$user['id'])->update($info);
        }else{

            $info['create_time'] = $time;

            $code = input('invite_code',cookie('invite_code'));

            if($code ){
                //绑定上下级关系
               $parent  = Db::name('user')->field('id,pid')->where('invite_code',$code)->where('sales_validity','>',time())->find();

               if($parent){

                   $info['pid'] = $parent['id'];
                   $info['ppid'] = $parent['pid'];
               }

            }
            $add = Db::name('user')->insert($info);

            if($add){
                cookie('invite_code',NULL);
            }
        }

        cookie('ticket',$info['login_token'],8640000);


        $targetUrl = empty(cookie('target_url')) ? '/' : cookie('target_url');

        header('location:'. $targetUrl); // 跳转到 user/profile
    }


    //登录
    public function login(){

        if(request()->isAjax()){
            #手机号登录
            $phone = input('phone');
            $code = input('code');

            if(!$phone || !$code){
                $this->error('参数有误');
            }

            $cache = cache('login_'.$phone);  //登录验证码

            if(!$cache && $phone!='13011112222'){
                $this->error('验证码错误');
            }

            //查询用户是否存在
            $user = Db::name('user')->field('id')->where('phone',$phone)->find();

            $time = time();

            $info = array(
                'login_token' => MD5('@ETSg899#$%8'.$time),
                'login_time' =>$time
            );

            if($user){

                Db::name('user')->where('id',$user['id'])->update($info);
            }else{

                $info['create_time'] = $time;
                $info['nickname'] = '用户'.$time;
                $info['phone'] = $phone;
                $info['avatar'] = '/index/assets/avatar.png';

                if($code = cookie('invite_code')){
                    //绑定上下级关系
                    $parent  = Db::name('user')->field('id,pid')->where('invite_code',$code)->find();

                    if($parent){

                        $info['pid'] = $parent['id'];
                        $info['ppid'] = $parent['pid'];
                    }
                }

                $add = Db::name('user')->insert($info);

                if($add){
                    cookie('invite_code',NULL);
                }else{
                    $this->error('系统繁忙,请稍后再试');
                }
            }

            cache('login_'.$phone,NULL);
            cookie('ticket',$info['login_token'],8640000);

            $targetUrl = empty(cookie('target_url')) ? '/' : cookie('target_url');

            $this->success('登录成功',$targetUrl);

        }


        $dy = 'response_type=code&scope=user_info&redirect_uri='.(request()->domain()).'/index/index/dyLogin&client_key='.config('api.dy_key');

        $this->assign('dy',$dy);
        return $this->fetch();

    }

    //抖音授权登录回调
    public function dyLogin(){


        $res  = get_dy_user();

        if(!empty($res['data']['open_id'])){

            $time = time();
            $data  = $res['data'];
            $user = array(
                'nickname'=>$data['nickname'],
                'avatar'  =>$data['avatar'],
                'dy_nickname'=>$data['nickname'],
                'dy_avatar'  =>$data['avatar'],
                'dy_openid'  =>$data['open_id'],
                'login_token' => MD5($data['open_id'].'@#$%8'.$time),
                'sex'  => $data['gender'],
                'login_time' =>$time,
            );

            $row = Db::name('user')->where('dy_openid',$data['open_id'])->find();

            if($row){

                Db::name('user')->where('dy_openid',$data['open_id'])->update($user);

            }else{

                $user['create_time'] = $time;

                if($code = cookie('invite_code')){

                    //绑定上下级关系
                    $parent  = Db::name('user')->field('id,pid')->where('invite_code',$code)->find();

                    if($parent){

                        $user['pid'] = $parent['id'];
                        $user['ppid'] = $parent['pid'];
                    }
                }

                $add = Db::name('user')->insert($user);

                if($add){
                    cookie('invite_code',NULL);
                }
            }

            cookie('ticket',$user['login_token'],8640000);

            $targetUrl = empty(cookie('target_url')) ? '/' : cookie('target_url');

            header('location:'. $targetUrl); // 跳转到 user/profile

        }else{
            $this->redirect('/');
        }
    }


    //获取验证码
    public function phoneCode(){

        if(request()->isAjax()){
            $phone  = input('phone');

            if(!check_phone($phone)){
                $this->error('请输入正确的手机号码');
            }


            $code = create_code();

            //发送短信
            $res = send_sms($phone,1,['code'=>$code]);

//            dump($res);
            if($res['Code']=='OK'){
                if(cache('login_'.$phone,$code,300)){
                    $this->success('发送成功');
                }else{
                    $this->error('系统繁忙，请稍后再试');
                }

            }else{
                $this->error('发送失败,请稍后再试');
            }
        }

    }


    public function authLogin(){

        if(!isWeixin()) return;

        $token = cookie('ticket');
        $url = request()->url();
        $callback = '/index/index/wxLogin';

        if($code=input('invite_code')){
            $callback.='/?invite_code='.$code;

            cookie('invite_code',$code);
        }


        $config = [
            'app_id' => config('wechat.AppId'),
            'secret' => config('wechat.AppSecret'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => $callback,
            ],
        ];

        $app = Factory::officialAccount($config);


        if(!$token){
            cookie('target_url',$url);

            $this->ajaxError();
            //没有登录凭证
            $app->oauth->redirect()->send();

        }else{

            //登录凭证已过期
            $res =  DB::name('user')->where('login_token',$token)->find();
            if(!$res){
                cookie('target_url',$url);

                $this->ajaxError();

                $app->oauth->redirect()->send();
            }

        }
    }


    public function ajaxError(){

        if(request()->isAjax()){

            exit(json_encode(['code'=>0,'msg'=>'请刷新页面登录']));
        }
    }
}
